package com.ssy.lingxi.system.service.impl;

import com.ssy.lingxi.common.constant.CommonConstant;
import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.manage.api.feign.paas.CurrencyPAASControllerFeign;
import com.ssy.lingxi.platform.manage.api.model.dto.currency.CurrencyPAASDTO;
import com.ssy.lingxi.system.dao.CurrencyRepository;
import com.ssy.lingxi.system.dao.SiteRepository;
import com.ssy.lingxi.system.dto.request.CurrencyAddRequest;
import com.ssy.lingxi.system.dto.request.CurrencyDeleteRequest;
import com.ssy.lingxi.system.dto.request.CurrencyListRequest;
import com.ssy.lingxi.system.dto.request.CurrencyUpdateRequest;
import com.ssy.lingxi.system.dto.response.CurrencyListResponse;
import com.ssy.lingxi.system.dto.response.MiddlegroundUserLoginResponse;
import com.ssy.lingxi.system.entity.Currency;
import com.ssy.lingxi.system.entity.Site;
import com.ssy.lingxi.system.service.CurrencyService;
import com.ssy.lingxi.system.utils.UserDetailsUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 币制设置业务处理
 *
 * @author wrc
 * @date 2020/5/25
 */
@Service
public class CurrencyServiceImpl implements CurrencyService {

    @Autowired
    UserDetailsUtil userDetailsUtil;

    @Autowired
    CurrencyRepository currencyRepository;
    @Resource
    SiteRepository siteRepository;
    @Resource
    CurrencyPAASControllerFeign currencyControllerFeign;

    /**
     * 查询币制列表
     *
     * @param request
     * @author wrc
     * @date 2020/5/25
     */
    @Override
    public Wrapper<PageData<CurrencyListResponse>> currencyList(CurrencyListRequest request) {
        PageData pageData = new PageData(0L, null);
        List<CurrencyListResponse> list = new ArrayList<>();
        Currency currency = new Currency();
        currency.setName(request.getName());
        currency.setNameEn(request.getNameEn());
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("nameEn", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<Currency> example = Example.of(currency, matcher);
        Page<Currency> all = currencyRepository.findAll(example, PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("id").ascending()));
        if (null != all && all.getTotalElements() > 0) {
            all.forEach(languageItem -> {
                CurrencyListResponse languageListResponse = new CurrencyListResponse();
                BeanUtils.copyProperties(languageItem, languageListResponse);
                list.add(languageListResponse);
            });
            pageData = new PageData(all.getTotalElements(), list);
        }
        return Wrapper.success(pageData);
    }

    /**
     * 添加币制列表
     *
     * @param httpServletRequest
     * @param request
     * @author wrc
     * @date 2020/5/26
     */
    @Transactional
    @Override
    public Wrapper<Currency> currencyAdd(HttpServletRequest httpServletRequest, CurrencyAddRequest request) {
        MiddlegroundUserLoginResponse loginUserDetails = userDetailsUtil.getLoginUserDetails(httpServletRequest);
        Currency currency = new Currency();
        BeanUtils.copyProperties(request, currency);
        currency.setCreateRoleId(loginUserDetails.getId());
        currency.setCreateTime(System.currentTimeMillis());
        currencyRepository.saveAndFlush(currency);

        CurrencyPAASDTO synCurrencyRequest = new CurrencyPAASDTO();
        BeanUtils.copyProperties(currency, synCurrencyRequest);
        Wrapper wrapper = currencyControllerFeign.add(synCurrencyRequest);

        return Wrapper.success(currency);
    }

    /**
     * 删除币制
     *
     * @param httpServletRequest
     * @param request
     * @author wrc
     * @date 2020/5/26
     */
    @Transactional
    @Override
    public Wrapper currencyDelete(HttpServletRequest httpServletRequest, CurrencyDeleteRequest request) {
        Optional<Currency> byId = currencyRepository.findById(request.getId());
        if (!byId.isPresent()) {
            return Wrapper.fail(ResponseCode.DATA_VALID_FAIL, "币制记录不存在");
        }
        if (byId.get().getState().equals(EnableDisableStatus.ENABLE.getCode())) {
            return Wrapper.fail(ResponseCode.BUSINESS_ERROR, "币制在有效状态");
        }
        currencyRepository.deleteById(request.getId());

        CurrencyPAASDTO synCurrencyRequest = new CurrencyPAASDTO();
        BeanUtils.copyProperties(request, synCurrencyRequest);
        Wrapper wrapper = currencyControllerFeign.delete(synCurrencyRequest);

        return Wrapper.success();
    }

    /**
     * 修改币制
     *
     * @param httpServletRequest
     * @param request
     * @author wrc
     * @date 2020/5/26
     */
    @Override
    public Wrapper currencyUpdate(HttpServletRequest httpServletRequest, CurrencyUpdateRequest request) {
        Optional<Currency> byId = currencyRepository.findById(request.getId());
        if (!byId.isPresent()) {
            return Wrapper.fail(ResponseCode.DATA_VALID_FAIL, "币制记录不存在");
        }
        if (byId.get().getState().equals(EnableDisableStatus.ENABLE.getCode())) {
            return Wrapper.fail(ResponseCode.DATA_VALID_FAIL, "币制非停用状态无法修改");
        }
        Currency currency = byId.get();
        BeanUtils.copyProperties(request, currency);
        currency.setUpdateTime(System.currentTimeMillis());
        currencyRepository.save(currency);

        CurrencyPAASDTO synCurrencyRequest = new CurrencyPAASDTO();
        BeanUtils.copyProperties(currency, synCurrencyRequest);
        Wrapper wrapper = currencyControllerFeign.update(synCurrencyRequest);

        return Wrapper.success();
    }

    /**
     * 停用币制
     *
     * @param request
     * @author wrc
     * @date 2020/6/3
     */
    @Transactional
    @Override
    public Wrapper currencyStop(CurrencyDeleteRequest request) {
        Optional<Currency> byId = currencyRepository.findById(request.getId());
        if (!byId.isPresent()) {
            return Wrapper.fail(ResponseCode.DATA_VALID_FAIL, "币制记录不存在");
        }
        List<Site> site = siteRepository.queryByCurrencyIdEquals(request.getId());
        if (null != site && site.size() > 0) {
            return Wrapper.fail("币制与站点有关联无法停用");
        }
        Currency currency = byId.get();
        currency.setState(EnableDisableStatus.DISABLE.getCode());
        currency.setUpdateTime(System.currentTimeMillis());
        currencyRepository.save(currency);

        CurrencyPAASDTO synCurrencyRequest = new CurrencyPAASDTO();
        BeanUtils.copyProperties(currency, synCurrencyRequest);
        Wrapper wrapper = currencyControllerFeign.state(synCurrencyRequest);

        return Wrapper.success();
    }

    /**
     * 查询所有币制
     *
     * @author wrc
     * @date 2020/6/3
     */
    @Override
    public Wrapper<List<Currency>> currencyAll() {
        List<Currency> currencies = currencyRepository.queryByStateEquals(CommonConstant.State.STATE_START);
        return Wrapper.success(currencies);
    }

    /**
     * 查询币制详情
     *
     * @param request
     * @author wrc
     * @date 2020/6/3
     */
    @Override
    public Wrapper<Currency> currencyDetails(CurrencyDeleteRequest request) {
        return Wrapper.success(currencyRepository.findById(request.getId()).get());
    }

}
